package com.itboye.sunsun.login.ui;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.itboye.sunsunhome.R;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.beans.PersonDataBean;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.controller.LoginController;
import com.itboye.sunsun.controller.LoginedState;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.utils.DebugLog;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

/**
 * 
 * @author
 * 
 */
public class LoginActivity extends BaseActivity implements OnClickListener {

	private Button login;
	private Button wechat;
	private Button forgetpassword;
	private Button smslogin;
	private Button regist;
	private EditText phoneedit;
	private EditText passwordedit;
	private String phone;
	private String password;
	private static final String APP_ID = "wxa30658c4f4f6bbf4";
	private IWXAPI api;
	public static String LOGINEXIT = "com.itboye.sunsun.exit";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		super.onCreate(savedInstanceState);
		api = WXAPIFactory.createWXAPI(App.ctx, APP_ID);

		// api.registerApp(APP_ID);
		setContentView(R.layout.activity_login);
		// startActivity(new Intent(getApplicationContext(),
		// MainActivity.class));

		// check();
		// IntentFilter filter=new IntentFilter("loginexit");
		// registerReceiver(emailBroadcastReceiver, filter);

		// 短信登录发送过来的广播
		IntentFilter filter1 = new IntentFilter(LOGINEXIT);
		registerReceiver(emailBroadcastReceiver, filter1);

	}

	// 检查是否登录过
	// public void check() {
	// if (IS_LOGINED) {
	// Intent intent = new Intent();
	// intent.setClass(LoginActivity.this, MainActivity.class);
	// startActivity(intent);
	// this.finish();
	// }
	// }

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.login:

			phone = phoneedit.getText().toString();
			password = passwordedit.getText().toString();

			// 检查手机号
			Pattern p = Pattern
					.compile("^((13[0-9])|(17\\d)|(14\\d)|(15[^4,\\D])|(18[0-9]))\\d{8}$");
			Matcher m = p.matcher(phone);
			if (TextUtils.isEmpty(phone)) {

				Toast.makeText(App.ctx, "请输入手机号", 0).show();
			} else if (TextUtils.isEmpty(password)) {
				Toast.makeText(App.ctx, "请输入密码", 0).show();
			} else {

				SPUtils.put(App.ctx, null, SPContants.USERNAME, phone);
				SPUtils.put(App.ctx, null, SPContants.PASSWORD, password);
				login();
			}
			break;
		case R.id.wechat:
			welongin();
			break;
		case R.id.regist:
			Intent intent = new Intent(this, RegistActivity.class);
			startActivity(intent);
			break;
//		case R.id.smslogin:
//			Intent intent1 = new Intent(this, SmsLoginActivity.class);
//			startActivity(intent1);
//			break;
		case R.id.forgetpassword:
			Intent intent2 = new Intent(this, ResetPasswordActivity.class);
			startActivity(intent2);
			break;
		default:
			break;
		}

	}

	private void welongin() {
		// Toast.makeText(App.ctx, "haha", 0).show();
		// send oauth request
		// SendAuth.Req req = new SendAuth.Req();
		// req.scope = "snsapi_userinfo";
		// req.state = "wechat_sdk_demo_test";
		// api.sendReq(req);
		final SendAuth.Req req = new SendAuth.Req();
		req.scope = "snsapi_userinfo";
		req.state = "none";
		req.transaction = "login";
		api.sendReq(req);

		// finish();

	}

	// //���˵�¼
	//
	// private UMAuthListener umAuthListener = new UMAuthListener() {
	// @Override
	// public void onComplete(SHARE_MEDIA platform, int action, Map<String,
	// String> data) {
	//
	// // data.get("nickname");
	// if (data != null) {
	// StringBuilder sb = new StringBuilder();
	// Set<String> keys = data.keySet();
	// for (String key : keys) {
	// if ("nickname".equals(key)) {
	// System.out.println("equals......");
	// }
	// sb.append("." + key + "=" + data.get(key).toString() + "\r\n");
	// }
	// Log.d("TestData", sb.toString());
	//
	// Toast.makeText(App.ctx, "......" + data.get("nickname").toString() +
	// ".....", 0).show();
	// Intent intent=new Intent(LoginActivity.this,BindWeChatActivity.class);
	// startActivity(intent);
	//
	// }
	//
	// }
	//
	// @Override
	// public void onError(SHARE_MEDIA platform, int action, Throwable t) {
	// Toast.makeText(getApplicationContext(), "Authorize fail",
	// Toast.LENGTH_SHORT).show();
	// }
	//
	// @Override
	// public void onCancel(SHARE_MEDIA platform, int action) {
	// Toast.makeText(getApplicationContext(), "Authorize cancel",
	// Toast.LENGTH_SHORT).show();
	// }
	//
	// };
	//
	// @Override
	// protected void onActivityResult(int requestCode, int resultCode, Intent
	// data) {
	// super.onActivityResult(requestCode, resultCode, data);
	// mShareAPI.onActivityResult(requestCode, resultCode, data);
	//
	// }
	//

	public void login() {
		MyJsonRequest<PersonDataBean> request = new MyJsonRequest.Builder<PersonDataBean>()
				.apiVer("100")
				.typeKey("BY_User_login")
				.param("username",
						(String) SPUtils.get(App.ctx, null,
								SPContants.USERNAME, ""))
				.param("password",
						(String) SPUtils.get(App.ctx, null,
								SPContants.PASSWORD, ""))
				.requestListener(new XRequestListener<PersonDataBean>() {

					@Override
					public void onResponse(PersonDataBean response) {
						// TODO Auto-generated method stub
						DebugLog.v("result", response.toString());

						// Intent intent = new Intent();
						// intent.setClass(LoginActivity.this,
						// MainActivity.class);
						// startActivity(intent);

						SPUtils.put(App.ctx, null, SPContants.WX_Openid,
								response.getWxopenid());
						SPUtils.put(App.ctx, null, SPContants.USERNAME,
								response.getUsername());
						SPUtils.put(App.ctx, null, SPContants.MOBILE,
								response.getMobile());
						SPUtils.put(App.ctx, null, SPContants.IS_LOGINED, true);
						SPUtils.put(App.ctx, null, SPContants.EMAIL,
								response.getEmail());
						SPUtils.put(App.ctx, null, SPContants.NICK,
								response.getNickname());
						SPUtils.put(App.ctx, null, SPContants.PASSWORD,
								response.getPassword());
						SPUtils.put(App.ctx, null, SPContants.USER_ID,
								response.getUid());
						SPUtils.put(App.ctx, null, SPContants.AVATAR_URL,
								response.getHead());
						LoginActivity.this.finish();
						LoginController.setLoginState(new LoginedState());
						// 发送广播通知更改头像
						Intent intent2 = new Intent("changeavart");
						sendBroadcast(intent2);
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
							Toast.makeText(App.ctx, "请求错误", 0).show();
					}
				}).build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	BroadcastReceiver emailBroadcastReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			LoginActivity.this.finish();

		};
	};

	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(emailBroadcastReceiver);
	};

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();

		overridePendingTransition(0, R.anim.anim_falldown);
	}
}
